/*************************************************************************
 *
 *  The Contents of this file are made available subject to the terms of
 *  the BSD license.
 *  
 *  Copyright (c) 2003 by Sun Microsystems, Inc.
 *  All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions
 *  are met:
 *  1. Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *  2. Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 *  3. Neither the name of Sun Microsystems, Inc. nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 *  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 *  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 *  FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 *  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 *  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 *  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
 *  OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 *  ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
 *  TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
 *  USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *     
 *************************************************************************/

#include "fann_addon.hpp"
#include <osl/diagnose.h>
#include <rtl/ustring.hxx>
#include <rtl/string.hxx>
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#include <com/sun/star/beans/PropertyValue.hpp>
#include <com/sun/star/frame/XFrame.hpp>
#include <com/sun/star/frame/XController.hpp>
#include <com/sun/star/awt/XToolkit.hpp>
#include <com/sun/star/awt/XWindowPeer.hpp>
#include <com/sun/star/awt/WindowAttribute.hpp>
#include <com/sun/star/awt/XMessageBox.hpp>
#include <cstdlib>
#include <cstdio>

using rtl::OUString;
using rtl::OString;
using namespace com::sun::star::uno;
using namespace com::sun::star::frame;
using namespace com::sun::star::awt;
using com::sun::star::lang::XMultiServiceFactory;
using com::sun::star::beans::PropertyValue;
using com::sun::star::util::URL;

#define SERVICE_NAME "com.sun.star.frame.ProtocolHandler"
#define MAIN_WINDOW_FUNCTION "Console"
#define PACKAGE_NAME "dk.leenissen.fann.OOorg"


static void ShowMessageBox( const Reference< XToolkit >& rToolkit, const Reference< XFrame >& rFrame, const OUString& aTitle, const OUString& aMsgText )
{
    if ( rFrame.is() && rToolkit.is() )
    {
        // describe window properties.
        WindowDescriptor                aDescriptor;
        aDescriptor.Type              = WindowClass_MODALTOP;
        aDescriptor.WindowServiceName = OUString( RTL_CONSTASCII_USTRINGPARAM( "infobox" ));
        aDescriptor.ParentIndex       = -1;
        aDescriptor.Parent            = Reference< XWindowPeer >( rFrame->getContainerWindow(), UNO_QUERY );
        aDescriptor.Bounds            = Rectangle(0,0,300,200);
        aDescriptor.WindowAttributes  = WindowAttribute::BORDER |
            WindowAttribute::MOVEABLE |
            WindowAttribute::CLOSEABLE;

        Reference< XWindowPeer > xPeer = rToolkit->createWindow( aDescriptor );
        if ( xPeer.is() ) {
            Reference< XMessageBox > xMsgBox( xPeer, UNO_QUERY );
            if ( xMsgBox.is() ) {
                xMsgBox->setCaptionText( aTitle );
                xMsgBox->setMessageText( aMsgText );
                xMsgBox->execute();
            }
        }
    }
}

/**
 * Called by the Office framework.
 * One-time initialization. We have to store the context information
 * given, like the frame we are bound to, into our members.
 */
void SAL_CALL FannAddon::initialize( const Sequence< Any >& aArguments ) throw ( Exception, RuntimeException)
{
    Reference < XFrame > xFrame;
    if ( aArguments.getLength() ) {
        aArguments[0] >>= xFrame;
        mxFrame = xFrame;
    }

    // Create the toolkit to have access to it later
    mxToolkit = Reference<XToolkit>( mxMSF->createInstance( 
                OUString( RTL_CONSTASCII_USTRINGPARAM("com.sun.star.awt.Toolkit" ) ) ), UNO_QUERY );
}

/**
 * Called by the Office framework.
 * We are ask to query the given URL and return a dispatch object if the URL
 * contains an Add-On command.
 */
    Reference<XDispatch> SAL_CALL FannAddon::queryDispatch( 
            const URL& aURL, const ::rtl::OUString& sTargetFrameName, sal_Int32 nSearchFlags ) throw( RuntimeException ) 
{
    Reference < XDispatch > xRet;
    if ( aURL.Protocol.compareToAscii( PACKAGE_NAME ":") == 0 ) {
        if ( aURL.Path.compareToAscii( MAIN_WINDOW_FUNCTION ) == 0 ) {
            xRet = this;
        }
    }

    return xRet;
}

/**
 * Called by the Office framework.
 * We are ask to execute the given Add-On command URL.
 */
void SAL_CALL FannAddon::dispatch( const URL& aURL, const Sequence < PropertyValue >& lArgs ) throw (RuntimeException) {
    if ( aURL.Protocol.compareToAscii( PACKAGE_NAME ":") == 0 ) {
        if ( aURL.Path.compareToAscii( MAIN_WINDOW_FUNCTION ) == 0 ) {
            createPluginProcess();
        }
    }
}

void FannAddon::createPluginProcess()
{
    const char* officeHome = std::getenv("OFFICE_HOME");
    if (!officeHome)
    {
        ShowMessageBox( mxToolkit, mxFrame, OUString( RTL_CONSTASCII_USTRINGPARAM("Error")),
            OUString(RTL_CONSTASCII_USTRINGPARAM("Set OFFICE_HOME environment variable to run the plugin!")));
    }
    else 
    {
        OString dir(officeHome);
        OString cmd("fann/fann_plugin --detached openoffice.org");
        OString fullCmd = dir + cmd;
        printf("%s\n", fullCmd.pData->buffer);
        system(fullCmd.pData->buffer);
    }
}

/**
 * Called by the Office framework.
 * We are ask to query the given sequence of URLs and return dispatch objects if the URLs
 * contain Add-On commands.
 */
Sequence <Reference<XDispatch> > SAL_CALL FannAddon::queryDispatches( 
            const Sequence < DispatchDescriptor >& seqDescripts ) throw( RuntimeException ) 
{
    sal_Int32 nCount = seqDescripts.getLength();
    Sequence < Reference < XDispatch > > lDispatcher( nCount );

    for( sal_Int32 i=0; i<nCount; ++i ) {
        lDispatcher[i] = queryDispatch( seqDescripts[i].FeatureURL, seqDescripts[i].FrameName, seqDescripts[i].SearchFlags );
    }
    return lDispatcher;
}

/**
 * Called by the Office framework.
 * We are ask to query the given sequence of URLs and return dispatch objects if the URLs
 * contain Add-On commands.
 */
void SAL_CALL FannAddon::addStatusListener( const Reference< XStatusListener >& xControl, const URL& aURL ) 
    throw (RuntimeException) 
{

}

/**
 * Called by the Office framework.
 * We are ask to query the given sequence of URLs and return dispatch objects if the URLs
 * contain Add-On commands.
 */
void SAL_CALL FannAddon::removeStatusListener( const Reference< XStatusListener >& xControl, const URL& aURL ) 
    throw (RuntimeException)
{

}

::rtl::OUString FannAddon_getImplementationName() throw (RuntimeException) {
    return ::rtl::OUString ( RTL_CONSTASCII_USTRINGPARAM ( IMPLEMENTATION_NAME ) );
}

sal_Bool SAL_CALL FannAddon_supportsService( const ::rtl::OUString& ServiceName ) throw (RuntimeException) {
    return ServiceName.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM ( SERVICE_NAME ) );
}

Sequence< ::rtl::OUString > SAL_CALL FannAddon_getSupportedServiceNames() throw (RuntimeException) {
    Sequence < ::rtl::OUString > aRet(1);
    ::rtl::OUString* pArray = aRet.getArray();
    pArray[0] =  ::rtl::OUString ( RTL_CONSTASCII_USTRINGPARAM ( SERVICE_NAME ) );
    return aRet;
}

Reference< XInterface > SAL_CALL FannAddon_createInstance( const Reference< XMultiServiceFactory > & rSMgr) throw( Exception ) {
    return (cppu::OWeakObject*) new FannAddon( rSMgr );
}

// XServiceInfo
::rtl::OUString SAL_CALL FannAddon::getImplementationName() throw (RuntimeException) {
    return FannAddon_getImplementationName();
}

sal_Bool SAL_CALL FannAddon::supportsService( const ::rtl::OUString& rServiceName ) throw (RuntimeException) {
    return FannAddon_supportsService( rServiceName );
}

Sequence< ::rtl::OUString > SAL_CALL FannAddon::getSupportedServiceNames() throw (RuntimeException) {
    return FannAddon_getSupportedServiceNames();
}
